﻿using System;
using System.Configuration;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Text;
using System.Web.Security;
using cvn.data;
using cvn.common;
using cvn.core;


namespace cvn.business
{
    public class CMembership 
    {

        private string _message;
        private string _userName;

        public string ErrorMessage
        {
            get { return _message; }
            set { _message = value; }
        }

        public string LoggedUserName
        {
            get { return _userName; }
            set { _userName = value; }
        }

        public CMembership()
        {

        }
       


        /// <summary>
        /// AuthorizeUser validates user based on useremail or userid and password
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="useEmail"></param>
        /// <returns></returns>
        public bool AuthorizeUser(string username, string password, bool useEmail = false)
        {
            
            if (useEmail)
            {
                username = Membership.GetUserNameByEmail(username);                                          
            }
            
            if (Membership.ValidateUser(username, password))
            {
                LoggedUserName = username;
                return true;
            }
            else
            {
                if (username.Length != 0)
                {

                    MembershipUser user = Membership.GetUser(username);
                    if (user != null)
                    {
                        if (user.IsLockedOut)
                        {
                            ErrorMessage = "The account is been locked, contact adminstrator";
                        }
                        else
                        {
                            SqlDataHelper sd = new SqlDataHelper();
                           
                            int InvalidAttempts = sd.GetFirstColumnAsInt("aspnet_Membership_GetFailedPasswordAttemptCount", username);
                            string value = SecurityHandler.GetMembershipSettings("maxInvalidPasswordAttempts");
                            if (value.Length != 0)
                            {

                                if (Convert.ToInt32(value) <= InvalidAttempts)
                                {
                                    ErrorMessage = "The account is been locked, contact adminstrator";
                                }
                                else
                                {
                                    ErrorMessage = "Invalid Password attempt, your account will be locked after " + (Convert.ToInt32(value) - InvalidAttempts) + " invalid try(s)";
                                }
                            }
                            else
                            {
                                ErrorMessage = "maxInvalidPasswordAttempts is missing, check configuration files";
                            }

                        }
                    }
                    else
                    {
                        ErrorMessage = "Invalid UserName / Email, please enter a valid username / email and try again";
                    }
                }
                else
                {
                    ErrorMessage = "Invalid UserName / Email, please enter a valid username / email and try again";
                }
                return false;
            }
        }


        public bool CreateNewUser(string username, string password, string email)
        {

            RegisteredUser Muser = new RegisteredUser();
            MembershipCreateStatus status = new MembershipCreateStatus();
            Muser.LoggedUser = Membership.CreateUser(username, password, email, "", "", false, out status);
            Muser.AccountValidateID = SecurityHandler.CreateHashCode(Guid.NewGuid().ToString());

            if (Muser.LoggedUser == null)
            {
                ErrorMessage = GetErrorMessage(status);
                return false;
            }
            else
            {
                ErrorMessage = "Account Created Succussfully, Please check your email to validate the account";
                return true;
            }
        }


       

        private string GetErrorMessage(MembershipCreateStatus status)
        {
            switch (status)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }


    }

        
    
}
